﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Match : TouchScript {

	public GameObject TargetMatcher;
	bool Selected = false;
	private int selectedFingerId = -1;
	public GameObject particlePreFab;
	// Use this for initialization
	void Start () {
		var matcher = this.transform.parent.GetChild(transform.parent.childCount-2);
		GameObject[] matchers = GetAllChildren(matcher).ToArray();

		int switchCount = Random.Range(0, matchers.Length);
		TargetMatcher = matchers[switchCount];
		this.renderer.material.color = TargetMatcher.GetComponent<SpriteRenderer>().color;
	}
	void OnMouseDrag()
	{
		Vector3 hit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
		this.transform.position = new Vector3(hit.x,hit.y,this.transform.position.z);
		
	}
	public override void Move (Vector3 pos, TouchPhase phase, int fingerId)
	{
		//First Click on Object
		if(phase == TouchPhase.Began && this.collider2D.OverlapPoint(new Vector3(pos.x,pos.y)))
		{
			Debug.Log("Touched " + fingerId);
			Selected = true;
			selectedFingerId = fingerId;
		}
		else if(phase == TouchPhase.Ended && selectedFingerId == fingerId)
		{
			Debug.Log("Ended " + fingerId);
			Selected = false;
			selectedFingerId = -1;
		}
		//Dragging the Object Add the logic here
		if(Selected && selectedFingerId == fingerId)
			this.transform.position = new Vector3(pos.x,pos.y,this.transform.position.z);
			
	}
	void OnMouseUp()
	{
		Vector3 hit = Camera.main.ScreenToWorldPoint(Input.mousePosition);

	//	this.transform.position = new Vector3(hit.x,hit.y,this.transform.position.z);
		
	}

	void OnTriggerEnter2D(Collider2D collider)
	{
		if(collider.name == TargetMatcher.name)
		{
			this.transform.parent.FindChild("Spawner").SendMessage("NewMatch");
			GameObject explosion = (GameObject)Instantiate(particlePreFab,this.transform.position,this.transform.rotation);
			explosion.particleSystem.startColor = this.renderer.material.color;
			Destroy(this.gameObject);
			Destroy(explosion,1);


		}
	}
			// Update is called once per frame
	void Update () {

	}

	List<GameObject> GetAllChildren(Transform parent)
	{
		List<GameObject> children = new List<GameObject>();

		for (int i = 0; i < parent.childCount; i++) {
				children.Add(parent.GetChild(i).gameObject);
				}
			
		return children;
	}
}
